﻿/*
 * stringlist.cpp
 *
 *  Created on: 2016-12-13
 *      Author: Dylan.Gao
 */

#include <dm/export.hpp>
#define DM_API_STRING DM_API_EXPORT

#include <dm/string/stringlist.hpp>

namespace dm{
namespace string{

CStringList::CStringList():m_es(new item_t){
}

CStringList::CStringList( const CStringList& l ){
	*m_es = *(l.m_es);
}

CStringList::~CStringList() {
	delete m_es;
}


CStringList& CStringList::operator =( const CStringList& strs ){
	*m_es = *(strs.m_es);
	return *this;
}

CStringList& CStringList::append( const char* str ){
	m_es->push_back(CString(str));
	return *this;
}

CStringList& CStringList::append( const CString& str ){
	m_es->push_back(str);
	return *this;
}

CStringList& CStringList::append( const CStringList& strs ){
	for( std::vector<CString>::const_iterator it=strs.m_es->begin();it!=strs.m_es->end();++it )
		m_es->push_back(*it);
	return *this;
}

size_t CStringList::totalSize()const{
	size_t s = 0;
	for( std::vector<CString>::const_iterator it=m_es->begin();it!=m_es->end();++it )
		s += it->len();

	return s;
}

CString CStringList::toString()const{
	CString rst;
	size_t p = totalSize();
	if( p==0 )
		return rst;


	rst.m_b = new char[p+1];
	rst.m_r = rst.m_b;

	p = 0;
	for( std::vector<CString>::const_iterator it=m_es->begin();it!=m_es->end();++it ){
		it->dump(rst.m_b+p);
		p += it->len();
	}

	return rst;
}

CString CStringList::toString( const char& c )const{
	CString rst;
	size_t p = totalSize()+m_es->size()-1;
	if( p<=0 )
		return rst;


	rst.m_b = new char[p+1];
	rst.m_r = rst.m_b;

	p = 0;
	for( std::vector<CString>::const_iterator it=m_es->begin();it!=m_es->end();++it ){
		if( p!=0 ){
			rst.m_b[p] = c;
			++p;
		}

		it->dump(rst.m_b+p);
		p += it->len();
	}

	return rst;
}

CString CStringList::toString( const char* str )const{
	CStringRef strRef(str);
	int l = strRef.len();

	CString rst;
	size_t p = totalSize()+(m_es->size()-1)*l;
	if( p<=0 )
		return rst;


	rst.m_b = new char[p+1];
	rst.m_r = rst.m_b;

	p = 0;
	for( std::vector<CString>::const_iterator it=m_es->begin();it!=m_es->end();++it ){
		if( p!=0 ){
			strRef.dump(rst.m_b+p);
			p += l;
		}
		
		it->dump(rst.m_b+p);
		p += it->len();
	}

	return rst;
}

/**
 * 对字符串进行切割
 * @param str 要切割的字符串
 * @param c 分隔符
 * @return
 */
CStringList& CStringList::split( const char* str,const char& c ){
	clear();

	CStringRef ref(str);
	if( ref.len()==0 )
		return *this;

	int s=0;
	do{
		int e = ref.nextChar(c,s);
		if( e==-1 ){
			// 没有分隔符
			append(CString(str+s));
			break;
		}else if( e==s ){
			// 第一个就是分隔符
			append(CString());
		}else{
			// 提前
			append(CString::fromString(str+s,e-s));
		}

		s = e + 1;
	}while( s<ref.len() );

	return *this;
}

CStringList& CStringList::split( const char* str,const char& c,int len ){
	CString strtmp(str,len);
	return split(strtmp.c_str(),c);
}

}
}
